package com.cn.mmd.controller;

import com.cn.mmd.model.Activity;
import com.cn.mmd.model.LogManage;
import com.cn.mmd.service.LogManageService;
import com.cn.mmd.service.ManageActivityService;
import com.cn.mmd.service.StudentActivityService;
import com.cn.mmd.tools.AliyunOssUtil;
import com.cn.mmd.tools.PictureUtil;
import com.sun.tools.internal.ws.processor.model.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 活动管理
 * Created by Administrator on 2016/7/27 0027.
 */

@Controller
@RequestMapping(value = "page/activityM")
public class ManageActivityController {

    @Autowired
    private ManageActivityService manageActivityService;

    @Autowired
    private LogManageService logManageService;

    @Autowired
    private StudentActivityService studentActivityService;


    /**
     * 添加活动，发布活动
     * @param request
     * @return
     */
    @RequestMapping(value = "/add")
    @ResponseBody public synchronized  Object addActivity (HttpServletRequest request,
                                             @RequestParam(value = "files", required = false) MultipartFile [] files
                                            , @RequestParam(value = "file1", required = false) MultipartFile  file1) throws ParseException {
        Map<String,Object> objectMap = new HashMap<String, Object>();
        String manageId = request.getParameter("manageId");
        String activityTitle = request.getParameter("activityTitle");
        String activityPictureURL = "";
        String activityPictureURLs = "";
        String activityTime = request.getParameter("activityTime");
        String activityLocation = request.getParameter("activityLocation");
        String activityType = "未审核";
        String activityContent = request.getParameter("activityContent");
        String activityCollege = request.getParameter("activityCollege");
        Integer functionAttendanceSum = Integer.parseInt(request.getParameter("functionAttendanceSum"));
        String activityCollegeNumber = request.getParameter("activityCollegeNumber");
        SimpleDateFormat simpleDateFormat =new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        Date date=simpleDateFormat .parse(activityTime);
        long timeStemp = date.getTime();
        simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm");
        activityTime = simpleDateFormat.format(timeStemp);
        Activity activity = new Activity();
        activity.setAcitvitytitle(activityTitle);
        activity.setActivitycollege(activityCollege);
        activity.setActivitylocation(activityLocation);
        activity.setActivitytime(activityTime);
        activity.setActivitytype(activityType);
        activity.setActivitycontent(activityContent);
        activity.setActivitycollegenumber(activityCollegeNumber);
        activity.setFunctionattendancesum(functionAttendanceSum);
        activity.setActivitycollegeid(manageId);
        System.out.println(1);
        if (manageActivityService.selectByAll(activity)==null) {
            if (file1==null){
                activity.setActivitypictureurl(activityPictureURL);
            }else {
                if (!file1.getOriginalFilename().equals("")){
                    String path=request.getSession().getServletContext().getRealPath("/") + "upload";
                    File targetFile;
                    String key = activityCollege+"-activity-"+file1.getOriginalFilename();
                    targetFile = new File(path,key);
                    if (!targetFile.exists()) {
                        targetFile.mkdirs();
                        try {
                            file1.transferTo(targetFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        targetFile.delete();
                        try {
                            file1.transferTo(targetFile);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    PictureUtil pictureUtil = new PictureUtil();
                    pictureUtil.zipWidthHeightImageFile(targetFile.getPath(), 720, 360, 4);
                    activityPictureURL = AliyunOssUtil.save(key,targetFile.getPath());
                    activity.setActivitypictureurl(activityPictureURL);
                    targetFile.delete();
                }

            }
            if (files == null) {
                activity.setActivitypictureurls(activityPictureURLs);
            } else {
                MultipartFile file;
                String url="";
                String path=request.getSession().getServletContext().getRealPath("/") + "upload";
                File targetFile;
                for (int i = 0 ; i < files.length ; i ++){
                    file = files[i];
                    if (!file.getOriginalFilename().equals("")){
                        String key = activityCollege+"-activity-"+file.getOriginalFilename();
                        targetFile = new File(path,key);
                        if (!targetFile.exists()) {
                            targetFile.mkdirs();
                            try {
                                file.transferTo(targetFile);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        } else {
                            targetFile.delete();
                            try {
                                file.transferTo(targetFile);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        PictureUtil pictureUtil = new PictureUtil();
                        pictureUtil.zipWidthHeightImageFile(targetFile.getPath(), 720, 360, 4);
                        activityPictureURL = AliyunOssUtil.save(key,targetFile.getPath());
                        if (i<files.length-1){
                          url =  activityPictureURL+","+url;
                        }else {
                            url = url + activityPictureURL;
                        }
                        targetFile.delete();
                    }
                    }
                    activity.setActivitypictureurls(url);
            }
            if (manageActivityService.insertSelective(activity)>0){
                objectMap.put("code",200);
                objectMap.put("message","成功");
            }else {
                objectMap.put("code",201);
                objectMap.put("message","添加失败");
            }
        }else {
            objectMap.put("code",202);
            objectMap.put("message", "请勿重复添加");
        }

        return objectMap;
    }

    /**
     * 修改活动信息
     * @param request
     * @return
     */
    @RequestMapping(value = "/upd")
    @ResponseBody public synchronized  Object updActivity(HttpServletRequest request){
        Map<String,Object> objectMap = new HashMap<String, Object>();
        String manageId = request.getParameter("manageId");
        Integer activityId = Integer.parseInt(request.getParameter("activityId"));
//        String activityTitle = request.getParameter("activityTitle");
//        String activityPictureURL = request.getParameter("activityPictureURL");
//        String activityTime = request.getParameter("activityTime");
//        String activityLocation = request.getParameter("activityLocation");
        String activityType = "审核通过";//request.getParameter("activityType");
//        String activityContent = request.getParameter("activityContent");
//        String activityCollege = request.getParameter("activityCollege");
        Activity activity = new Activity();
        activity.setActivityid(activityId);
//        activity.setAcitvitytitle(activityTitle);
//        activity.setActivitycollege(activityCollege);
//        activity.setActivitylocation(activityLocation);
//        activity.setActivitytime(activityTime);
        activity.setActivitytype(activityType);
//        activity.setActivitycontent(activityContent);
//        activity.setActivitypictureurl(activityPictureURL);
        if (manageActivityService.updateByPrimaryKeySelective(activity)>0){
            objectMap.put("code",200);
            objectMap.put("message","成功");
            Date date = new Date();
            SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String logTime=time.format(date);
            LogManage logManage = new LogManage();
            logManage.setLogtime(logTime);
            logManage.setManageid(manageId);
            logManage.setLogcontent("审核了一个活动:"+activityId);
            logManageService.insertSelective(logManage);
        }else {
            objectMap.put("code",201);
            objectMap.put("message","修改失败");
        }

        return objectMap;
    }

    /**
     * 删除一个活动
     * @param request
     * @return
     */
    @RequestMapping(value = "/del")
    @ResponseBody public synchronized  Object delActivity(HttpServletRequest request){
        Map<String,Object> objectMap = new HashMap<String, Object>();
        Integer activityId = Integer.parseInt(request.getParameter("activityId"));
        String manageId = request.getParameter("manageId");
        if ( manageActivityService.deleteByPrimaryKey(activityId)>0){
            manageActivityService.deleteByActId(activityId);
            objectMap.put("code",200);
            objectMap.put("message","成功");
            Date date = new Date();
            SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            String logTime=time.format(date);
            LogManage logManage = new LogManage();
            logManage.setLogtime(logTime);
            logManage.setManageid(manageId);
            logManage.setLogcontent("删除了一个活动:"+activityId);
            logManageService.insertSelective(logManage);
        }else {
            objectMap.put("code",201);
            objectMap.put("message","删除失败");
        }
        return objectMap;
    }

    @RequestMapping(value = "/selects")
    public synchronized  @ResponseBody Object selectStudentActivity(HttpServletRequest request) {
        Map<String,Object> objectMap =new HashMap<String, Object>();
        List<Map> mapList = new ArrayList<Map>();
        Map<String,Object> map ;
        String acitvityTitle= request.getParameter("activityTitle");
        Integer statrow = Integer.parseInt(request.getParameter("startrow"));
        Integer pageSize = Integer.parseInt(request.getParameter("pageSize"));
        Activity activity = new Activity();
        activity.setPageSize(pageSize);
        activity.setStartrow(statrow);
        activity.setAcitvitytitle(acitvityTitle);
        List<Activity> activityList =studentActivityService.selectByActivityName(activity);
        if (activityList!=null&&activityList.size()>0){
            for (int i = 0 ; i < activityList.size();i++){
                activity = activityList.get(i);
                map = new HashMap<String, Object>();
                map.put("activityTitle",activity.getAcitvitytitle());
                map.put("activityType", activity.getActivitytype());
                map.put("activityCollege", activity.getActivitycollege());
                map.put("activityTime",activity.getActivitytime());
                map.put("activityId",activity.getActivityid()+"");
                map.put("activityLocation", activity.getActivitylocation());
                map.put("activityPictureUrl",activity.getActivitypictureurl());
                map.put("functionAttendance",activity.getFunctionattendance());
                mapList.add(map);
            }
            activity = new Activity();
            activity.setAcitvitytitle(acitvityTitle);
            int i1 = manageActivityService.countLimitNum(activity);
            objectMap.put("total", i1);
            objectMap.put("data",mapList);
            objectMap.put("message","成功");
            objectMap.put("code",200);
        }else {
            activity = new Activity();
            activity.setAcitvitytitle(acitvityTitle);
            int i1 = manageActivityService.countLimitNum(activity);
            objectMap.put("total", i1);
            objectMap.put("message","查看失败");
            objectMap.put("code",201);
        }
        return objectMap;
    }
}
